package command

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"

	"github.com/fatih/color"

	"gitee.com/csingo/csingo/resource/version"
)

type VersionCommand struct{}

func (i *VersionCommand) Desc() *CommandDesc {
	return &CommandDesc{
		Name: "version",
		Methods: []*CommandMethod{
			{
				Name:   "show",
				Desc:   "查看工具当前版本",
				Params: []*CommandParams{},
			},
			{
				Name: "update",
				Desc: "更新工具版本",
				Params: []*CommandParams{
					{
						Name:     "to",
						Desc:     "指定版本号，默认最新版",
						Optional: true,
					},
				},
			},
		},
	}
}

func (i *VersionCommand) Show() {
	ver, _ := version.Asset("version/version")
	color.Set(color.FgHiCyan)
	fmt.Println(string(ver))
	color.Set(color.FgWhite)
}

func (i *VersionCommand) Update(to string) {
	log.Println("版本升级")
	ver, _ := version.Asset("version/version")
	log.Printf("当前版本: %s", string(ver))
	if to == "" {
		versionBody, err := http.Get("https://gitee.com/csingo/csingo/raw/master/version/version")
		if err != nil {
			log.Fatalln(err)
		}
		var versionByte []byte
		versionByte, err = ioutil.ReadAll(versionBody.Body)
		log.Printf("最新版本: %s", string(versionByte))
		to = string(versionByte)
	}

	log.Printf("下载安装: %s\n\n", to)
	cmd := exec.Command("go", "install", fmt.Sprintf("gitee.com/csingo/csingo@%s", to))
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout
	cmd.Run()
}
